﻿using System; 
using Com.Mathphoenix.MapApps;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Com.Mathphoenix.MapApps.NerdDinner.Models;


namespace  Com.Mathphoenix.MapApps.NerdDinner.Models
{
    public class DinnerRepository:IDinnerRepository
    {
        private NerdDinnerDataContext db = new NerdDinnerDataContext();


        // Query Methods
        public IQueryable<Dinner> FindAllDinners()
        {
            return db.Dinners;
        }
        public IQueryable<Dinner> FindUpcomingDinners()
        {
            return from dinner in db.Dinners
                   where dinner.EventDate > DateTime.Now
                   orderby dinner.EventDate
                   select dinner;
        }

        public Dinner GetDinner(int id)
        {
            return db.Dinners.SingleOrDefault(d => d.DinnerID == id);
        }

        // Insert/Delete
        public void Add(Dinner dinner)
        {
            db.Dinners.InsertOnSubmit(dinner);
        }


        public void Delete(Dinner dinner)
        {
            db.RSVPs.DeleteAllOnSubmit(dinner.RSVP);
            db.Dinners.DeleteOnSubmit(dinner);
        }

        // Pesistence
        public void Save()
        {
            db.SubmitChanges();   
        }



        public IQueryable<Dinner> FindByLocation(float latitude, float longitude)
        {
            var dinners = from dinner in FindUpcomingDinners()
                          join i in db.NearestDinners(latitude, longitude)
                          on dinner.DinnerID equals i.DinnerID
                          select dinner;
            return dinners;
        }
    }
}
